package ink.onei.framework.web.service;

import ink.onei.common.core.domain.BaseEntity;
import ink.onei.common.core.domain.entity.Seller;
import ink.onei.common.core.domain.entity.SysRole;
import ink.onei.common.core.domain.entity.SysUser;
import ink.onei.system.service.ISysMenuService;
import ink.onei.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @author nekotako
 */
@Component
public class SysPermissionService {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取角色数据权限
     *
     * @param object 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(BaseEntity object) {
        Set<String> roles = new HashSet<>();
        if (object instanceof SysUser user) {
            // 管理员拥有所有权限
            if (user.isAdmin()) {
                roles.add("admin");
            } else {
                roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
            }
        } else if (object instanceof Seller seller) {
            roles.addAll(roleService.selectRolePermissionBySellerId(seller.getSellerId()));
        }// else if (object instanceof Client) {
//            Client client = (Client) object;
//            roles.addAll(roleService.selectRolePermissionBySellerId(client.getClientId()));
//        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param object 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(BaseEntity object) {
        Set<String> perms = new HashSet<>();
        if (object instanceof SysUser user) {
            // 管理员拥有所有权限
            if (user.isAdmin()) {
                perms.add("*:*:*");
            } else {
                List<SysRole> roles = user.getRoles();
                if (!CollectionUtils.isEmpty(roles)) {
                    // 多角色设置permissions属性，以便数据权限匹配权限
                    for (SysRole role : roles) {
                        Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                        role.setPermissions(rolePerms);
                        perms.addAll(rolePerms);
                    }
                } else {
                    perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
                }
            }
        } else if (object instanceof Seller) {
            SysRole role = roleService.selectRoleById(3L);
            perms.addAll(menuService.selectMenuPermsBySellerId());
            role.setPermissions(perms);
        }
        return perms;
    }
}
